// Copyright (c) 2023 Presto Labs Pte. Ltd.
// Author: tianqiang

#pragma once

#include <memory>
#include <sstream>
#include <string>

#include "coin2/exchange/base/symbology/spot_product.h"
#include "coin2/exchange/maicoin/symbology/currency.h"

namespace coin2::exchange::maicoin::symbology {

class MaicoinProduct : public base::symbology::SpotProduct<MaicoinCurrency, MaicoinProduct>,
                       public base::symbology::ProductFromStrMixin<MaicoinProduct> {
 public:
  MaicoinProduct(const MaicoinCurrency& base, const MaicoinCurrency& quote)
      : SpotProduct(
            base,
            quote,
            ToNativeProduct(base, quote),
            ToNativeProduct(base, quote),
            base::market::ExchangeType::Maicoin) {}

 public:
  static std::unique_ptr<MaicoinProduct> FromNativeStrImpl(
      const std::string& native_product,
      int64_t resolve_timestamp) {
    std::unique_ptr<MaicoinCurrency> base_ptr;
    std::unique_ptr<MaicoinCurrency> quote_ptr;
    bool success = ParseNativeProduct(native_product, resolve_timestamp, &base_ptr, &quote_ptr);

    if (!success) {
      return {};
    }

    return std::make_unique<MaicoinProduct>(*base_ptr, *quote_ptr);
  }

 private:
  static bool ParseNativeProduct(
      const std::string& product_str,
      int64_t resolve_timestamp,
      std::unique_ptr<MaicoinCurrency>* base_ptr,
      std::unique_ptr<MaicoinCurrency>* quote_ptr) {
    static const std::string quotes[] = {"btc", "twd", "usdt"};

    for (const auto& quote_cand : quotes) {
      if (StringEndsWith(product_str, quote_cand)) {
        size_t base_len = product_str.size() - quote_cand.size();
        std::string base = product_str.substr(0, base_len);
        *base_ptr = MaicoinCurrency::FromNativeStrNoThrow(base, resolve_timestamp);
        *quote_ptr = MaicoinCurrency::FromNativeStrNoThrow(quote_cand, resolve_timestamp);
        return true;
      }
    }
    return false;
  }

  static std::string ToNativeProduct(const MaicoinCurrency& base, const MaicoinCurrency& quote) {
    using base::market::MarketType;
    std::stringstream ss;
    ss << base.native_currency(MarketType::Spot) << quote.native_currency(MarketType::Spot);
    return ss.str();
  }
};

}  // namespace coin2::exchange::maicoin::symbology
